package org.icnmasjid.member.webapp.action;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.icnmasjid.member.webapp.action.BaseFormController;
import org.icnmasjid.member.model.AccessGroup;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;

public class AccessGroupFormController extends BaseFormController {
    public AccessGroupFormController() {
        setCommandName("accessGroup");
        setCommandClass(AccessGroup.class);
    }

    protected Object formBackingObject(HttpServletRequest request)
    throws Exception {
        String id = request.getParameter("id");
        AccessGroup accessGroup = null;

        if (!StringUtils.isEmpty(id)) {
            accessGroup = (AccessGroup) manager.getObject(AccessGroup.class, new Integer(id));
        } else {
            accessGroup = new AccessGroup();
        }

        return accessGroup;
    }

    public ModelAndView onSubmit(HttpServletRequest request,
                                 HttpServletResponse response, Object command,
                                 BindException errors)
    throws Exception {
        if (log.isDebugEnabled()) {
            log.debug("entering 'onSubmit' method...");
        }

        AccessGroup accessGroup = (AccessGroup) command;
        boolean isNew = (accessGroup.getId() == null);
        Locale locale = request.getLocale();

        if (request.getParameter("delete") != null) {
            manager.removeObject(AccessGroup.class, accessGroup.getId());

            saveMessage(request, getText("accessGroup.deleted", locale));
        } else {
            manager.saveObject(accessGroup);

            String key = (isNew) ? "accessGroup.added" : "accessGroup.updated";
            saveMessage(request, getText(key, locale));

            if (!isNew) {
                return new ModelAndView("redirect:editAccessGroup.html", "id", accessGroup.getId());
            }
        }

        return new ModelAndView(getSuccessView());
    }
}
